package ua.amsoft.brelok.widget;

import java.util.Calendar;

import ua.amsoft.brelok.constant.Constants;
import ua.amsoft.brelok.manager.PreferencesManager;
import ua.amsoft.brelok.service.UpdateService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class UpdateStartReceiver extends BroadcastReceiver {
    
    public static final String START_RECEIVER_ACTION = "UpdateStartReceiverAction";
    
    private static final String TAG = UpdateStartReceiver.class.getName();
    
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.i(UpdateStartReceiver.TAG, "UpdateStartReceiver received intent and started execution");
        final PreferencesManager preferencesManager = new PreferencesManager();
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        
        final Intent updateServiceIntent = new Intent(context, UpdateService.class);
        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final PendingIntent pendingIntentToStart = PendingIntent.getService(context, 0,
                updateServiceIntent, 0);
        final String interval = preferencesManager.getPrefByName(context,
                Constants.PREF_UPDATE_INTERVAL, "no interval");
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                Long.valueOf(interval), pendingIntentToStart);
        Log.i(UpdateStartReceiver.TAG, "Update interval: " + interval + " milliseconds");
        Log.i(UpdateStartReceiver.TAG, "UpdateService starting at: "
                + calendar.getTime().toString());
        Log.i(UpdateStartReceiver.TAG, "UpdateStartReceiver finished execution");
    }
    
}
